package com.gxm.jar.guava;

import com.google.common.base.Optional;
import org.junit.Test;


public class OptionalDemo {
    @Test
    public void demo1(){
        //one
        Optional<Integer> possible = Optional.fromNullable(5);  //创建允许null值的Optional

        //two
        Integer nubmerone=4;
        Optional<Integer> integerOptional = Optional.of(nubmerone);//若引用为null则快速失败触发java.lang.NullPointerException

        //three
        Optional<Integer> nullOptional=Optional.absent();//创建引用缺失的Optional实例,就是为NULL的
    }

    @Test
    public void demo2(){
        Optional<Integer> possible = Optional.fromNullable(5);  //创建允许null值的Optional
        if(possible.isPresent()){//包含的引用非null的（引用存在），返回true
            System.out.println("possible.value："+possible.get());//包含的引用缺失(null)，则抛出java.lang.IllegalStateException
        }else{
            System.out.println("possible is null");
        }
    }

    @Test
    public void demo3(){
        Optional<Integer> possible = Optional.fromNullable(null);  //创建允许null值的Optional
        if(possible.isPresent()){//包含的引用非null的（引用存在），返回true
            System.out.println("possible.value："+possible.get());//包含的引用缺失(null)，则抛出java.lang.IllegalStateException
        }else{
            System.out.println("possible is null");
            possible.get();
        }
    }

    @Test
    public void demo4(){
        Optional<Integer> nulloptional = Optional.absent();//null就是缺少的意思
        Integer value = nulloptional.or(3);
        nulloptional = null;
        System.out.println("【if nulloptional is null,return is 3,others is itself't value】value ="+value);

        Optional<Integer> optional = Optional.of(5);
        Integer value2 = optional.or(3);
        System.out.println("【if optional is null,return is 3,others is itself't value】value ="+value2);
    }
}
